import { ElMessage } from "element-plus";
import { Http } from "./http";
import { FieldRule, showToast } from "vant";
import type { interForm } from './type'
import Schema, { InternalRuleItem, RuleItem } from 'async-validator';

const isPhone = (window as any).isPhone
export class Form extends Http {
    id?: number;
    data: any;
    select: any;
    labels: Map<string, interForm>;
    url: { setdata: string; adddate: string; upddate: string; };
    rule?: Schema["rules"];
    isDetail: boolean;
    selectlabel?: { [key: string]: { show: boolean, title: string, label: string, type?: 'cascader' | 'multiple', value: string, children?: string } }
    constructor() {
        super()
        this.id = undefined
        this.url = {
            setdata: '',
            adddate: '',
            upddate: ''
        }
        this.isDetail = true
        this.labels = new Map()
        this.data = new Proxy({}, this.proxyValue)
        this.select = {}
        return this.utils_proxy_set(this, (target, key, value) => {
            if (key === 'show' && !value) {
                this.id = undefined
                this.data = new Proxy({}, this.proxyValue)
            }
        })
    }
    getVantRule(rule: RuleItem[]): FieldRule[] {
        return rule.map(item => {
            const { required, message, pattern, validator } = item
            return {
                required, message, pattern, validateEmpty: false, validator: validator ? (value: any, rule: InternalRuleItem, ...arg: any) => {
                    //@ts-ignore
                    return validator(rule, value, ...arg)
                } : () => true
            } as FieldRule
        })
    }
    async setData(): Promise<any> {
        const id = this.id
        if (!id) {
            throw new Error("获取详情时id不存在");
        }
        const res = await this.request(this.url.setdata, { parames: { id } })
        if (res) {
            this.data = new Proxy(res, this.proxyValue)
            return res
        }
        return false
    }
    async updateData(object: { upload?: string, jsons?: string[], unToast?: boolean } = {}): Promise<any> {
        const { id } = this
        //结构取消联动，防止json类别改变时报错
        const data = { ...this.data }
        const err = await this._validater(data)
        if (err) return
        const { upload, jsons } = object
        if (upload) {
            const url = data[upload]
            // if (Array.isArray(url)) {
            //     const res = await Promise.all(url.map(item => {
            //         if (/^blob:/.test(item)) {
            //             return this.upload(item)
            //         } else {
            //             return item.replace(/http:\/\/(\d{3}|.){7}:\d*/, '')
            //         }
            //     }))
            //     if (res.includes('error')) return
            //     data[upload] = res
            // } else {
            //     if (/^blob:/.test(url)) {
            //         const res = await this.upload(url)
            //         if (res === 'error') return
            //         data[upload] = res
            //     } else {
            //         data[upload] = url?.replace(/http:\/\/(\d{3}|.){7}:\d*/, '')
            //     }
            // }
        }
        if (jsons) {
            jsons.forEach(item => {
                data[item] = data[item] && JSON.stringify(data[item])
            })
        }
        if (id) {
            const res = await this.request(this.url.upddate, { method: 'POST', parames: { id }, data: { ...data } })
            if (res) {
                return res
            }
        } else {
            const res = await this.request(this.url.adddate, { method: 'POST', data })
            if (res) {
                this.id = id
                return res
            }
        }
        return false
    }
    async _validater(data: any) {
        if (!this.rule) return false
        try {
            const validator = new Schema(this.rule);
            await validator.validate(data, { first: true })
            return false
        } catch (error: any) {
            if (Object.hasOwn(error, 'errors')) {
                const message = error.errors[0].message
                if (isPhone) {
                    //滑动到不符合规则的输入框
                    const errDom = this.errkey ? document.getElementById(this.errkey) : null
                    errDom?.scrollIntoView({ block: 'end' })
                    errDom?.setAttribute('style', 'border-bottom:1px solid rgb(238, 10, 36)')
                    setTimeout(() => {
                        errDom?.setAttribute('style', 'border:none')
                    }, 1000);
                    showToast({ message })
                } else {
                    ElMessage.error({ message })
                }
            } else {
                console.log(error)
                throw error
            }
            return true
        }
    }
}